﻿using Activity.Data;
using Activity.DBHelper;
using Activity.Helper;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Activity.API
{
    public class ShopInspectionResultsHandler
    {
        protected MyDbHelperA mydb = new MyDbHelperA();
        #region 获取头部数据
        public List<BaseModel> GetBaseModelTab(string tifid, string shopName, string checkDate)
        {
            if (string.IsNullOrEmpty(shopName) || string.IsNullOrEmpty(checkDate))
                return null;
            try
            {
                string sql = $@" 
                         select   mast.tif_id,mast.tif_checkCount,tif_shopName=(vvs.OperationAreaName+' '+mast.tif_shopName),shopName=mast.tif_shopName,mast.tif_shopCode,vshop.kddate
		                ,mast.ProblemNum as tif_questionCount,mast.new_tif_score as tif_score
			                ,mast.tif_checkDate,mast.tif_week,weekWeather=(isnull(mast.tif_week,'')+' '+ isnull(mast.tif_weather,'')),mast.tif_captain
			                ,lastscore=las.tif_score,lastCheckDate=las.tif_checkDate,lasquestionCount=las.tif_questionCount ,mast.tif_storeManager/*店长*/,mast.tif_shopManager/*店经理*/
			                ,mast.tif_shopLevel,mast.tif_supervisor,mast.tif_summary
                             from V_t_inspection_finishMaster mast 
                             inner join V_ShopList vshop on vshop.CompanyID='KM' and vshop.shopcode=mast.tif_shopCode
                             left join KM_V_Ins_ShopList vvs on vvs.ShopCode=mast.tif_shopCode
                             left join t_inspection_finishDetail detail on mast.tif_id=detail.tid_id
                             left join (select  tif_checkDate,tif_score=new_tif_score,tif_shopCode,userId,ProblemNum as tif_questionCount from V_t_inspection_finishMaster las 
			                 WHERE YEAR(tif_checkDate)=YEAR(GETDATE()) )  las 
                             on  las.tif_shopCode=mast.tif_shopCode and las.tif_checkDate<mast.tif_checkDate and mast.userId=las.userId
                             where YEAR(mast.tif_checkDate)=YEAR(GETDATE())";

                if (!string.IsNullOrEmpty(tifid))
                {
                    sql += string.Format(" AND mast.tif_id={0}", tifid);
                }
                if (!string.IsNullOrEmpty(shopName))
                {
                    shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                    if (Regex.IsMatch(shopName[0].ToString(), @"[\u4e00-\u9fbb]"))
                        sql += string.Format(" AND mast.tif_shopName like '%{0}%'", shopName);
                    else
                    {
                        shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                        sql += string.Format(" AND mast.tif_shopName like '%{0}%'", shopName);
                    }
                }
                if (!string.IsNullOrEmpty(checkDate))
                {
                    checkDate = System.Web.HttpUtility.UrlDecode(checkDate, System.Text.Encoding.UTF8);
                    checkDate = Convert.ToDateTime(checkDate).ToString("yyyy-MM-dd");
                    sql += string.Format(" AND CONVERT(VARCHAR(10),mast.tif_checkDate,120)=CONVERT(VARCHAR(10),'{0}',120) ", checkDate);
                }
                sql += "order by detail.ins_id ASC ";
                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<BaseModel> dc = new DataConver<BaseModel>();
                List<BaseModel> list = dc.FillModel(ds);
                if (list != null && list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        item.tif_SummaryList = GetTinSummary(item.tif_id);
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }
        #endregion

        #region 获取店铺巡检总结 
        /// <summary>
        /// 获取店铺总结
        /// </summary>
        /// <param name="tif_id"></param>
        /// <returns></returns>
        private IList<TinSummary> GetTinSummary(int? tif_id)
        {
            IList<TinSummary> list = null;
            if (tif_id.HasValue)
            {
                using (ActivityEntities activityEntities = new ActivityEntities())
                {
                    string[] strList = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };
                    string cheIndex = string.Join(",", strList);
                    list = activityEntities.t_inspection_summary.Where(c => c.tif_id == tif_id).Select(c => new TinSummary { tis_id = c.tis_id, tif_id = c.tif_id, tis_projectProblem = c.tis_projectProblem, tis_problemDescription = c.tis_problemDescription, tis_advice = c.tis_advice }).OrderBy(c => SqlFunctions.CharIndex(DbFunctions.Left(c.tis_projectProblem, 1), cheIndex)).ToList();
                }
            }
            return list;
        }
        #endregion

        #region  获取人员状况检查,陈列VI标准检查.... 9大类
        public List<StatusCheck> GetStatusCheck(string tifid, string shopName, string checkDate, string ins_parentName)
        {

            try
            {
                if (string.IsNullOrEmpty(shopName) || string.IsNullOrEmpty(checkDate))
                    return null;
                var bucketName = ConfigurationManager.AppSettings["image-oss-BucketName"];
                //string sql = @"
                //            select setting.ins_checkContext,setting.ins_score,detail.tid_points,detail.tid_remarks From t_inspection_setting setting 
                //            inner join t_inspection_finishDetail detail on setting.ins_id=detail.ins_id
                //            inner join t_inspection_finishMaster mast on mast.tif_id=detail.tif_id
                //            left join t_inspection_img img on  img.tid_id=detail.tid_id and img.img_type=1
                //            left join kmImages kimg on kimg.ID=img.Img_ID
                //            where  setting.isRemove=0 ";


                string sql = string.Format(@"  select detail.tid_id,setting.ins_checkContext,setting.ins_score,tid_points=isnull(detail.tid_points,0)
		,tid_remarks=isnull(detail.tid_remarks,''),setting.ins_checkContextRemark,setting.ins_parentName,setting.ins_parentCode,w_id=ISNULL(w_id,0)
		    from V_t_inspection_finishMaster mast
        left join t_inspection_finishDetail detail on mast.tif_id=detail.tif_id 
        inner join t_inspection_setting setting  on setting.ins_id=detail.ins_id and  setting.isRemove=0 
		left join t_ins_workorderMaster wm on wm.tid_id=detail.tid_id
        --left join t_inspection_img img on  img.tid_id=detail.tid_id and img.img_type=1
        --left join kmImages kimg on kimg.ID=img.Img_ID
            where  setting.isRemove=0  ");
                // where  setting.isRemove=0 --AND setting.ins_parentName='{0}' ", ins_parentName);
                if (!string.IsNullOrEmpty(tifid))
                {
                    sql += string.Format(" AND mast.tif_id={0}", tifid);
                }
                if (!string.IsNullOrEmpty(shopName))
                {
                    if (Regex.IsMatch(shopName[0].ToString(), @"[\u4e00-\u9fbb]"))
                        sql += string.Format(" AND mast.tif_shopName like '%{0}%'", shopName);
                    else
                    {
                        shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                        sql += string.Format(" AND mast.tif_shopName like '%{0}%'", shopName);
                    }
                }
                if (!string.IsNullOrEmpty(checkDate))
                {
                    checkDate = System.Web.HttpUtility.UrlDecode(checkDate, System.Text.Encoding.UTF8);
                    checkDate = Convert.ToDateTime(checkDate).ToString("yyyy-MM-dd");
                    sql += string.Format(" AND CONVERT(VARCHAR(10),mast.tif_checkDate,120)=CONVERT(VARCHAR(10),'{0}',120) ", checkDate);
                }
                sql += " order by setting.ins_parentCode asc";
                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<StatusCheck> dc = new DataConver<StatusCheck>();
                List<StatusCheck> list = dc.FillModel(ds);
                if (list == null || list.Count <= 0) return null;//为空，不处理图片，直接返回数据

                //查询图片
                #region 图片处理
                string idList = "'";
                foreach (var item in list)
                {
                    idList += item.tid_id + "','";
                }
                if (string.IsNullOrWhiteSpace(idList) || idList == "'") return list;//为空，不处理图片，直接返回数据
                idList = idList.TrimEnd('\'');
                idList = idList.TrimEnd(',');
                List<StatusImgList> imgList = GetImgList(idList);
                if (imgList == null || imgList.Count <= 0) return list;//图片为空，不处理，直接返回数据

                List<StatusCheck> retList = new List<StatusCheck>();
                foreach (var item in list)
                {
                    StatusCheck sc = new StatusCheck();
                    sc.ins_checkContext = item.ins_checkContext;
                    sc.ins_checkContextRemark = item.ins_checkContextRemark;
                    sc.ins_score = item.ins_score;
                    sc.tid_points = item.tid_points;
                    sc.tid_remarks = item.tid_remarks;
                    sc.tid_id = item.tid_id;
                    sc.w_id = item.w_id;
                    sc.ins_parentName = item.ins_parentName;
                    sc.ins_parentCode = item.ins_parentCode;
                    for (int j = 0; j < imgList.Count; j++)
                    {
                        //id相等，且为第一张
                        if (item.tid_id == imgList[j].tid_id && ((j + 1) % 3 == 1))
                        {
                            sc.Img1 = ImageHelper.GetOssUrl(bucketName, imgList[j].Url);
                            sc.title1 = imgList[j].Title;
                        }
                        //id相等，且为第二张
                        if (item.tid_id == imgList[j].tid_id && ((j + 1) % 3 == 2))
                        {
                            sc.Img2 = ImageHelper.GetOssUrl(bucketName, imgList[j].Url);
                            sc.title2 = imgList[j].Title;
                        }
                        //id相等，且为第三张
                        if (item.tid_id == imgList[j].tid_id && ((j + 1) % 3 == 0))
                        {
                            sc.Img3 = ImageHelper.GetOssUrl(bucketName, imgList[j].Url);
                            sc.title3 = imgList[j].Title;
                        }
                    }
                    retList.Add(sc);
                }
                return retList;
                #endregion
            }
            catch (Exception ex)
            {
                return null;
            }


        }
        #endregion


        public List<SettingList> getSettingList(string tifid, string shopName, string checkDate)
        {
            if (string.IsNullOrEmpty(tifid) || string.IsNullOrEmpty(checkDate))
                return null;
            try
            {
                string sql = @"
                 select  distinct setting.ins_parentName,ins_parentCode  from t_inspection_finishMaster mast
                left join t_inspection_finishDetail detail on mast.tif_id = detail.tif_id and mast.isRemove = 0 
                left join t_inspection_setting setting  on setting.ins_id = detail.ins_id and setting.isRemove = 0
                where setting.isRemove = 0 and mast.isRemove = 0 ";

                if (!string.IsNullOrEmpty(tifid))
                {
                    sql += string.Format(" AND mast.tif_id={0}", tifid);
                }
                if (!string.IsNullOrEmpty(shopName))
                {
                    shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                    sql += string.Format(" AND mast.tif_shopName like '%{0}%'", shopName);
                }
                if (!string.IsNullOrEmpty(checkDate))
                {
                    checkDate = System.Web.HttpUtility.UrlDecode(checkDate, System.Text.Encoding.UTF8);
                    checkDate = Convert.ToDateTime(checkDate).ToString("yyyy-MM-dd");
                    sql += string.Format(" AND CONVERT(VARCHAR(10),mast.tif_checkDate,120)=CONVERT(VARCHAR(10),'{0}',120) ", checkDate);
                }
                sql += @"group by ins_parentName,ins_parentCode
                order by ins_parentCode asc";
                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<SettingList> dc = new DataConver<SettingList>();
                List<SettingList> list = dc.FillModel(ds);
                return list;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// 查询所有图片列表
        /// </summary>
        /// <param name="tifIdList">tif_id数组</param>
        /// <returns></returns>
        public List<StatusImgList> GetImgList(string tifIdList)
        {
            try
            {
                string sql = string.Format(@"
                     select detail.tid_id,kimg.Url,kimg.Title From t_inspection_img img
                     inner join kmImages kimg on img.Img_ID=kimg.ID
                     left join t_inspection_finishDetail detail on detail.tid_id=img.tid_id
                     where img.img_type=1 and detail.tid_id in({0})", tifIdList);

                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<StatusImgList> dc = new DataConver<StatusImgList>();
                List<StatusImgList> list = dc.FillModel(ds);
                return list;

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }

        }


        //查询门店名称
        public List<ShopList> GetShopNameList(string shopName = "")
        {
            try
            {
                //mast.tif_shopCode,
                string sql = @" select distinct mast.tif_shopName from t_inspection_finishMaster mast 
                                 inner join  V_ShopList vs on mast.tif_shopCode=vs.shopcode and mast.isRemove = 0 
                                 where CompanyID='KM' and mast.isRemove = 0 ";
                //if (!string.IsNullOrEmpty(shopName))
                //{
                //    shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                //    sql += string.Format(" AND( mast.tif_shopName like '%{0}%' or mast.tif_shopCode like  '%{0}%')", shopName);
                //}
                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<ShopList> dc = new DataConver<ShopList>();
                List<ShopList> list = dc.FillModel(ds);
                return list;

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public List<TimeList> GetTimeList(string shopName = "")
        {
            try
            {
                //mast.tif_shopCode,
                string sql = @" select distinct tif_checkDate=CONVERT(nvarchar(10),mast.tif_checkDate,120) from t_inspection_finishMaster mast 
                                 inner join  V_ShopList vs on mast.tif_shopCode=vs.shopcode and mast.isRemove = 0 
                                 where CompanyID='KM' and mast.isRemove = 0  ";
                if (!string.IsNullOrEmpty(shopName))
                {
                    shopName = System.Web.HttpUtility.UrlDecode(shopName, System.Text.Encoding.UTF8);
                    sql += string.Format(" AND( mast.tif_shopName like '%{0}%' or mast.tif_shopCode like  '%{0}%')", shopName);
                }
                sql += " order by  CONVERT(nvarchar(10),mast.tif_checkDate,120) asc  ";

                DataSet ds = mydb.DM_GetDateSet(sql);
                DataConver<TimeList> dc = new DataConver<TimeList>();
                List<TimeList> list = dc.FillModel(ds);
                return list;

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="tifid"></param>
        /// <param name="shopName"></param>
        /// <param name="checkDate"></param>
        /// <returns></returns>
        /// writer:ljj
        /// createdate:2018-03-23
        public string Export(string tifid, string shopName, string checkDate)
        {
            try
            {
                var strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //获取或设置包含该应用程序的目录的名称。
                if (!Directory.Exists(strPath + "upfile"))
                {
                    Directory.CreateDirectory(strPath + "upfile"); //不存在就创建文件夹 }
                }
                if (!Directory.Exists(strPath + "upfile\\download"))
                {
                    Directory.CreateDirectory(strPath + "upfile\\download"); //不存在就创建文件夹 }
                }
                var dyInfo = new DirectoryInfo(strPath + "upfile\\download");

                var fileName = $"{shopName}_{checkDate}_巡店检查表.doc";

                var filePath = $"{strPath}upfile\\download\\{fileName}";
                var filePath2 = $"upfile\\download\\{fileName}";

                if (!File.Exists(filePath))
                {

                    var shopBase = GetBaseModelTab(tifid, shopName, checkDate).FirstOrDefault();
                    if (shopBase != null)
                    {
                        var list = GetStatusCheck(tifid, shopName, checkDate, "");

                        var parentList = list.GroupBy(d => new { d.ins_parentCode, d.ins_parentName });

                        //创建document对象  
                        var doc = new XWPFDocument();

                        //创建段落对象  
                        var title1 = doc.CreateParagraph();
                        title1.Alignment = ParagraphAlignment.CENTER; //字体居中  

                        //创建run对象  
                        //本节提到的所有样式都是基于XWPFRun的，  
                        //你可以把XWPFRun理解成一小段文字的描述对象，  
                        //这也是Word文档的特征，即文本描述性文档。  
                        //来自Tony Qu http://tonyqus.sinaapp.com/archives/609  
                        var runTitle1 = title1.CreateRun();
                        runTitle1.SetBold(true);
                        runTitle1.SetText("2018年KM终端督导巡店检查表");
                        runTitle1.FontSize = 25;
                        runTitle1.FontFamily = "宋体";

                        var title2 = doc.CreateParagraph();
                        title2.Alignment = ParagraphAlignment.RIGHT;
                        var runTitle2 = title2.CreateRun();
                        runTitle2.SetText("此次为本年第");
                        runTitle2.FontSize = 12;
                        runTitle2.FontFamily = "宋体";
                        runTitle2 = title2.CreateRun();
                        runTitle2.SetText($"{shopBase.tif_checkCount}");
                        runTitle2.FontSize = 12;
                        runTitle2.FontFamily = "宋体";
                        runTitle2.SetColor("#ff4500");
                        runTitle2 = title2.CreateRun();
                        runTitle2.SetText("次巡店");
                        runTitle2.FontSize = 12;
                        runTitle2.FontFamily = "宋体";
                        runTitle2.SetColor("#000000");


                        var tableShopBase = doc.CreateTable(3, 10);
                        tableShopBase.Width = (int)(1000 * 5);
                        //tableShopBase.SetColumnWidth(0, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(1, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(2, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(3, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(4, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(5, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(6, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(7, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(8, 716); /* 设置列宽 */
                        //tableShopBase.SetColumnWidth(9, 716); /* 设置列宽 */

                        tableShopBase.GetRow(0).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "门店名称",
                            ParagraphAlignment.CENTER, TextAlignment.AUTO, 10, true, 8));
                        tableShopBase.GetRow(0).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_shopName, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(0).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "门店代码",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(0).GetCell(3).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_shopCode, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(0).GetCell(4).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "开业时间",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(0).GetCell(5).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.kddate.ToString("yyyy-MM-dd"), ParagraphAlignment.CENTER, TextAlignment.CENTER, 10,
                            false, 8));
                        tableShopBase.GetRow(0).GetCell(6).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "查出问题数", ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(0).GetCell(7).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_questionCount.ToString(), ParagraphAlignment.CENTER, TextAlignment.CENTER, 10,
                            false, 8));
                        tableShopBase.GetRow(0).GetCell(8).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "本次得分",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(0).GetCell(9).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_score.ToString(), ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false,
                            8));

                        tableShopBase.GetRow(1).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "查店时间",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(1).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_checkDate.ToString("yyyy-MM-dd"), ParagraphAlignment.CENTER,
                            TextAlignment.CENTER,
                            10, false, 8));
                        tableShopBase.GetRow(1).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "星期/天气", ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(1).GetCell(3).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.weekWeather, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(1).GetCell(4).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "上次查店时间", ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(1).GetCell(5).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.lastCheckDate == new DateTime()
                                ? "---"
                                : shopBase.lastCheckDate.ToString("yyyy-MM-dd"), ParagraphAlignment.CENTER,
                            TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(1).GetCell(6).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "上次问题数", ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(1).GetCell(7).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.lastCheckDate == new DateTime() ? "---" : shopBase.lasquestionCount.ToString(),
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(1).GetCell(8).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "上次得分",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(1).GetCell(9).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.lastCheckDate == new DateTime() ? "---" : shopBase.lastscore.ToString(),
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));

                        tableShopBase.GetRow(2).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "店长",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(2).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_storeManager, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(2).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "领班",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(2).GetCell(3).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_captain, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(2).GetCell(4).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "店经理",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(2).GetCell(5).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_shopManager, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(2).GetCell(6).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "店铺等级",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(2).GetCell(7).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_shopLevel, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));
                        tableShopBase.GetRow(2).GetCell(8).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            "检查督导",
                            ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                        tableShopBase.GetRow(2).GetCell(9).SetParagraph(ExportHelper.SetCellText(doc, tableShopBase,
                            shopBase.tif_supervisor, ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, false, 8));

                        foreach (var item in parentList)
                        {
                            var itemTitle = doc.CreateParagraph();
                            itemTitle.Alignment = ParagraphAlignment.LEFT;
                            var runItemTitle = itemTitle.CreateRun();
                            runItemTitle.SetText(
                                $"{item.Key.ins_parentName}({item.Sum(d => d.ins_score)})分             ");
                            runItemTitle.FontSize = 8;
                            runItemTitle.FontFamily = "宋体";
                            runItemTitle.SetBold(true);
                            runItemTitle = itemTitle.CreateRun();
                            runItemTitle.SetText("查出问题数： ");
                            runItemTitle.FontSize = 8;
                            runItemTitle.FontFamily = "宋体";
                            runItemTitle = itemTitle.CreateRun();
                            runItemTitle.SetText($"{item.Count(d => d.tid_points != 0)} ");
                            runItemTitle.FontSize = 8;
                            runItemTitle.FontFamily = "宋体";
                            runItemTitle.SetColor("#ff4500");
                            runItemTitle = itemTitle.CreateRun();
                            runItemTitle.SetText("扣分： ");
                            runItemTitle.FontSize = 8;
                            runItemTitle.FontFamily = "宋体";
                            runItemTitle.SetColor("#000000");
                            runItemTitle.SetText($"{item.Sum(d => d.tid_points)}");
                            runItemTitle.FontSize = 8;
                            runItemTitle.FontFamily = "宋体";
                            runItemTitle.SetColor("#ff4500");

                            var itemTable = doc.CreateTable(item.Count() + 1, 6);
                            //itemTable.Width = (int)(1000 * 7.16);
                            //itemTable.SetColumnWidth(0, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(1, 2200); /* 设置列宽 */
                            //itemTable.SetColumnWidth(2, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(3, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(4, 2200); /* 设置列宽 */
                            //itemTable.SetColumnWidth(5, 2200); /* 设置列宽 */

                            itemTable.GetRow(0).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "序号",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            itemTable.GetRow(0).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "检查项目",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            itemTable.GetRow(0).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "分值",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            itemTable.GetRow(0).GetCell(3).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "扣分",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            itemTable.GetRow(0).GetCell(4).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "备注",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            itemTable.GetRow(0).GetCell(5).SetParagraph(ExportHelper.SetCellText(doc, itemTable, "图片",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));

                            var i = 1;
                            foreach (var it in item)
                            {
                                itemTable.GetRow(i).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                    $"{i}",
                                    ParagraphAlignment.LEFT, TextAlignment.CENTER, 10, false, 8));
                                itemTable.GetRow(i).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                    it.ins_checkContext, ParagraphAlignment.LEFT, TextAlignment.CENTER, 10, false, 8));
                                itemTable.GetRow(i).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                    it.ins_score.ToString(), ParagraphAlignment.LEFT, TextAlignment.CENTER, 10, false,
                                    8));
                                itemTable.GetRow(i).GetCell(3).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                    it.tid_points == 0 ? "" : it.tid_points.ToString(), ParagraphAlignment.LEFT,
                                    TextAlignment.CENTER, 10, false, 8));
                                itemTable.GetRow(i).GetCell(4).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                    it.tid_remarks, ParagraphAlignment.LEFT, TextAlignment.CENTER, 10, false, 8));
                                if (it.title1 == null)
                                {
                                    itemTable.GetRow(i).GetCell(5).SetParagraph(ExportHelper.SetCellText(doc, itemTable,
                                        "",
                                        ParagraphAlignment.LEFT, TextAlignment.CENTER, 10));
                                }
                                else
                                {
                                    var urlList = new List<string> { it.Img1, it.Img2, it.Img3 };
                                    var imgList = new List<string> { it.title1, it.title2, it.title3 };
                                    itemTable.GetRow(i).GetCell(5).SetParagraph(ExportHelper.SetCellPicture(doc,
                                        itemTable, urlList, imgList, ParagraphAlignment.LEFT, (int)(100.0 * 9525),
                                        (int)(100.0 * 9525)));
                                }
                                i++;
                            }
                        }

                        if (shopBase.tif_SummaryList.Any())
                        {
                            var summaryTitle = doc.CreateParagraph();
                            summaryTitle.Alignment = ParagraphAlignment.LEFT;
                            var runSummaryTitle = summaryTitle.CreateRun();
                            runSummaryTitle.SetText("巡店总结");
                            runSummaryTitle.FontSize = 8;
                            runSummaryTitle.FontFamily = "宋体";
                            runSummaryTitle.SetBold(true);

                            var summaryTable = doc.CreateTable(shopBase.tif_SummaryList.Count() + 1, 3);
                            //itemTable.Width = (int)(1000 * 7.16);
                            //itemTable.SetColumnWidth(0, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(1, 2200); /* 设置列宽 */
                            //itemTable.SetColumnWidth(2, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(3, 180); /* 设置列宽 */
                            //itemTable.SetColumnWidth(4, 2200); /* 设置列宽 */
                            //itemTable.SetColumnWidth(5, 2200); /* 设置列宽 */

                            summaryTable.GetRow(0).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc, summaryTable, "项目问题",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            summaryTable.GetRow(0).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc, summaryTable, "问题汇总描述",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));
                            summaryTable.GetRow(0).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc, summaryTable, "建议/改善方案",
                                ParagraphAlignment.CENTER, TextAlignment.CENTER, 10, true, 8));

                            var i = 1;
                            foreach (var itemSummary in shopBase.tif_SummaryList)
                            {
                                summaryTable.GetRow(i).GetCell(0).SetParagraph(ExportHelper.SetCellText(doc,
                                    summaryTable, itemSummary.tis_projectProblem, ParagraphAlignment.LEFT,
                                    TextAlignment.CENTER, 10, false, 8));
                                summaryTable.GetRow(i).GetCell(1).SetParagraph(ExportHelper.SetCellText(doc,
                                    summaryTable, itemSummary.tis_problemDescription, ParagraphAlignment.LEFT,
                                    TextAlignment.CENTER, 10, false, 8));
                                summaryTable.GetRow(i).GetCell(2).SetParagraph(ExportHelper.SetCellText(doc,
                                    summaryTable, itemSummary.tis_advice, ParagraphAlignment.LEFT, TextAlignment.CENTER,
                                    10, false, 8));
                                i++;
                            }
                        }
                        //foreach(var m_CTTbl in doc.Document.body.GetTblArray())
                        //{
                        //    //m_CTTbl.AddNewTblPr().jc = new CT_Jc();
                        //    m_CTTbl.AddNewTblPr().AddNewTblW().w = "7160"; //表宽
                        //    m_CTTbl.AddNewTblPr().AddNewTblW().type = ST_TblWidth.pct;
                        //    m_CTTbl.AddNewTblPr().tblpPr = new CT_TblPPr(); //表定位
                        //    m_CTTbl.AddNewTblPr().tblpPr.tblpX = "100"; //表左上角坐标
                        //    m_CTTbl.AddNewTblPr().tblpPr.tblpY = "100";
                        //    m_CTTbl.AddNewTblPr().tblpPr.tblpXSpec = ST_XAlign.left; //若不为“Null”，则优先tblpX，即表由tblpXSpec定位
                        //    //m_CTTbl.AddNewTblPr().tblpPr.tblpYSpec = ST_YAlign.bottom;//若不为“Null”，则优先tblpY，即表由tblpYSpec定位  
                        //    //m_CTTbl.AddNewTblPr().tblpPr.leftFromText = (ulong)180;
                        //    //m_CTTbl.AddNewTblPr().tblpPr.rightFromText = (ulong)180;
                        //    m_CTTbl.AddNewTblPr().tblpPr.vertAnchor = ST_VAnchor.text;
                        //    m_CTTbl.AddNewTblPr().tblpPr.horzAnchor = ST_HAnchor.page;
                        //}

                        var fs = new FileStream(filePath, FileMode.Create);
                        doc.Write(fs);
                        fs.Close();

                        //获取文件夹下所有的文件
                        foreach (FileInfo feInfo in dyInfo.GetFiles())
                        {
                            //判断文件日期是否小于2小时，是则删除
                            if (feInfo.CreationTime < DateTime.Now.AddHours(-1))
                                feInfo.Delete();
                        }
                    }
                    else
                    {
                        return null;
                    }
                }
                return filePath2;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }
    }

    [Serializable]
    public class BaseModel
    {
        //编号
        public int tif_id { get; set; }
        //本年第n次巡店
        public int tif_checkCount { get; set; }
        //门店名称
        public string tif_shopName { get; set; }
        //门店代码
        public string tif_shopCode { get; set; }
        //开业时间
        public DateTime kddate { get; set; }
        //查出问题数
        public int tif_questionCount { get; set; }
        //本次得分
        public decimal tif_score { get; set; }
        //查店时间
        public DateTime tif_checkDate { get; set; }
        //星期/天气
        public string weekWeather { get; set; }
        //上次查店时间
        public DateTime lastCheckDate { get; set; }
        //上次得分
        public decimal lastscore { get; set; }
        //上次问题数
        public int lasquestionCount { get; set; }
        //店长
        public string tif_storeManager { get; set; }
        //店经理
        public string tif_shopManager { get; set; }
        //店铺等级
        public string tif_shopLevel { get; set; }
        //检查督导
        public string tif_supervisor { get; set; }
        //领班
        public string tif_captain { get; set; }
        /// <summary>
        /// 巡店总结集合
        /// </summary>
        public IList<TinSummary> tif_SummaryList { get; set; }
        public string shopName { get; set; }
    }

    /// <summary>
    /// 巡检总结
    /// </summary>
    [Serializable]
    public class TinSummary
    {
        /// <summary>
        /// 主键
        /// </summary>
        public int? tis_id { get; set; }
        /// <summary>
        /// 巡检主单
        /// </summary>
        public int? tif_id { get; set; }
        /// <summary>
        /// 项目问题
        /// </summary>
        public string tis_projectProblem { get; set; }
        /// <summary>
        /// 问题汇总描述
        /// </summary>
        public string tis_problemDescription { get; set; }
        /// <summary>
        /// 建议/改善方案
        /// </summary>
        public string tis_advice { get; set; }
    }

    [Serializable]
    public class StatusCheck
    {
        public string ins_checkContext { get; set; }
        public string ins_checkContextRemark { get; set; }
        public decimal ins_score { get; set; }
        public decimal tid_points { get; set; }
        public string tid_remarks { get; set; }
        public string ins_parentName { get; set; }
        public string ins_parentCode { get; set; }
        public int w_id { get; set; }
        public int tid_id { get; set; }
        public string Img1 { get; set; }
        public string title1 { get; set; }
        public string Img2 { get; set; }
        public string title2 { get; set; }
        public string Img3 { get; set; }
        public string title3 { get; set; }

    }

    public class StatusImgList
    {
        public string Url { get; set; }
        public int tid_id { get; set; }
        public string Title { get; set; }
    }

    public class ShopList
    {
        //门店名称
        public string tif_shopName { get; set; }
    }

    public class SettingList
    {
        public string ins_parentName { get; set; }
    }
    public class TimeList
    {
        //门店名称
        public string tif_checkDate { get; set; }

    }
}

